#include "internal.h"
#include "ProximitySensor.h"
#include "ProximitySensor.tmh"
#include "RS232Connection.h" // for SENSOR_READING_MIN
#include "RS232Target.h" // for SensorState
#include "WpdObjectProperties.h" 

const PROPERTYKEY g_SupportedProximityProperties[] =
{
    SENSOR_PROPERTY_TYPE,
    SENSOR_PROPERTY_STATE,
    SENSOR_PROPERTY_CURRENT_REPORT_INTERVAL,
    SENSOR_PROPERTY_MIN_REPORT_INTERVAL,
    SENSOR_PROPERTY_PERSISTENT_UNIQUE_ID,
    SENSOR_PROPERTY_MANUFACTURER, 
    SENSOR_PROPERTY_MODEL,
    SENSOR_PROPERTY_SERIAL_NUMBER,
	SENSOR_PROPERTY_FRIENDLY_NAME,
    SENSOR_PROPERTY_DESCRIPTION, 
    SENSOR_PROPERTY_CONNECTION_TYPE,
    WPD_FUNCTIONAL_OBJECT_CATEGORY,
};

const PROPERTYKEY g_SupportedProximityDataFields[] =
{
    SENSOR_DATA_TYPE_TIMESTAMP,
    SENSOR_DATA_TYPE_HUMAN_PROXIMITY_METERS,
};

ProximitySensor::ProximitySensor(WpdObjectProperties* pWpdObjectProperties): 
	SensorBase(pWpdObjectProperties) 
{
	m_strSensorName		= SENSOR_PROXIMITY_FRIENDLY_NAME;
	m_strSensorId		= SENSOR_PROXIMITY_ID;
	m_gdSensorUniqueId	= SENSOR_PROXIMITY_GUID;
	m_gdSensorCategory	= SENSOR_CATEGORY_BIOMETRIC;
	m_gdSensorType		= SENSOR_TYPE_HUMAN_PROXIMITY;
}

VOID ProximitySensor::AddPropertyKeys(
	IPortableDeviceKeyCollection* pKeys)
{
    if (pKeys != NULL)
    {
        for (DWORD dwIndex = 0; dwIndex < ARRAYSIZE(g_SupportedProximityProperties); dwIndex++)
        {
            pKeys->Add(g_SupportedProximityProperties[dwIndex] );
        }
    }
}

VOID ProximitySensor::AddDataFieldKeys(
	IPortableDeviceKeyCollection* pKeys)
{
    if (pKeys != NULL)
    {
        for (DWORD dwIndex = 0; dwIndex < ARRAYSIZE(g_SupportedProximityDataFields); dwIndex++)
        {
            pKeys->Add(g_SupportedProximityDataFields[dwIndex] );
        }
    }
}

/// 
/// RetrieveProximity returns the distance in centimeters from a 
/// 64-bit proximity-sensor reading. The reading has the following
/// format: 41500121 where the first byte is the identifier
/// the second and third bytes contain packet length and the 
/// remaining bytes contain the proximity in centimeters followed by 
/// sensor interval. ("00121" is 121 centimeters.)
///
int RetrieveProximity(__int64 llVal)
{
    __int64 llTemp=0;
    int iTemp=0;

    llTemp = llVal - 41500000;
    iTemp = (int)llTemp;
    return iTemp;
}

HRESULT ProximitySensor::OnGetDataValues(
    PROPERTYKEY &Key,
    IPortableDeviceValues*         pValues)
{
    HRESULT hr = S_OK;
    int iProximity = 0;

    // Set proximity sensor data   
    if (IsEqualPropertyKey(Key, SENSOR_DATA_TYPE_HUMAN_PROXIMITY_METERS))
    {
        iProximity = RetrieveProximity((__int64)m_llSensorReading);
        hr = pValues->SetUnsignedIntegerValue(SENSOR_DATA_TYPE_HUMAN_PROXIMITY_METERS, iProximity);
    }
	return hr;
}